package com.wandian.weather.mvvm.mapweather;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.TimeUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.weather.R;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.databinding.MapActivityWeatherBinding;
import com.wandian.weather.tools.WeatherUtil;


/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 地图天气
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_MAP_WEATHER)
public class MapWeatherActivity extends BaseMVVMActivity<MapWeatherViewModel> implements AMap.OnMarkerClickListener,
        AMap.OnMapLoadedListener, AMap.OnMapClickListener, LocationSource, AMapLocationListener, AMap.OnCameraChangeListener , GeocodeSearch.OnGeocodeSearchListener{
    private MapActivityWeatherBinding dataBinding;
    private MapView mMapView;
    private AMap mAMap;
    private Marker mGPSMarker;             //定位位置显示
    private AMapLocation location;
    private OnLocationChangedListener mListener;
    //你编码对象
    private GeocodeSearch  geocoderSearch;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private MarkerOptions markOptions;
    private LatLng latLng;
    private String addressName;
    private float zoomToNumber = 13;

    private WeatherInformationBean cloudBean;
    private String[] weatherQualityArray = {"良", "优", "轻", "中", "重"};
    private int[] weatherQualityRes = {R.drawable.button_green_circle_solid_selector, R.drawable.button_blue_circle_solid_selector, R.drawable.button_yellow_circle_solid_selector, R.drawable.button_red_circle_ball, R.drawable.button_sys_circle_ball};
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.map_activity_weather);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initDataView();
        initClink();
        //初始化map资源
        initMap(savedInstanceState);
        //更具时间更换背景
        TimeUtils.customHomeBgByTime(this,dataBinding.llMapWeather);
    }

    private void initDataView(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("地图天气");
        mViewModel.weatherInformationBean.observe(this,bean->{
            if(!UIUtils.isEmpty(bean)){
                this.cloudBean = bean;
                notifyUiData();
            }
        });
    }

    /**
     * 更新视图
     */
    private void notifyUiData() {
        if (cloudBean == null) {
            return;
        }
        if (cloudBean.getBase() != null) {
            judge();
            dataBinding.tvTodayKq.setText(""+aqiStr);

            if (!TextUtils.isEmpty(cloudBean.getBase().getUltraviolet())) {
                dataBinding.tvMapWeatherUltraviolet.setText(cloudBean.getBase().getUltraviolet());
            }
            dataBinding.tvTmp.setText(cloudBean.getBase().getLtemp() +"~"+ cloudBean.getBase().getHtemp() + "°C");
            dataBinding.tvWeather.setText(cloudBean.getBase().getWeather()+"");
            dataBinding.tvMapWeatherTemperature.setText(cloudBean.getMinutely_description()+"");
            dataBinding.tvMapWeatherDesc.setText(cloudBean.getBase().getStemp());
            dataBinding.tvMapWeatherFeel.setText(cloudBean.getBase().getPm25() + "μg/m³");
            dataBinding.tvMapWeatherPress.setText("实时温度:" + cloudBean.getBase().getStemp() + "°C");
            dataBinding.tvMapWeatherHumidity.setText(cloudBean.getBase().getSD());
//            ImageLoader.displayByResource(this, img_map_weather, "mipmap", "map" + cloudBean.getBase().getImg_num());
            dataBinding.imgMapWeather.setImageResource(WeatherUtil.getWeatherStateImage(cloudBean.getBase().getImg_num(), false));
        }
        dataBinding.tvMapWeatherPlacePress.setText(cloudBean.getWind().getSpeed() + "km/h");
    }

    private String aqiStr = "";

    private void judge() {
        try {
            float aqi = Float.parseFloat(cloudBean.getBase().getAqi());
            if (aqi <= 50) {
                aqiStr = "优";
            } else if (aqi > 50 && aqi <= 100) {
                aqiStr = "良";
            } else if (aqi > 100 && aqi <= 150) {
                aqiStr = "轻";
            } else if (aqi > 150 && aqi <= 200) {
                aqiStr = "中";
            } else {
                aqiStr = "重";
            }
            setWeatherQualityBack();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据空气质量类型设置空气质量背景
     */

    private void setWeatherQualityBack() {
        for (int i = 0; i < weatherQualityArray.length; i++) {
            if (aqiStr.contains(weatherQualityArray[i])) {
                dataBinding.tvMapWeatherQuality.setText(weatherQualityArray[i]);
                dataBinding.tvMapWeatherQuality.setBackgroundResource(weatherQualityRes[i]);
                break;
            }
        }
    }

    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v ->   finish());
    }

    private void initMap(Bundle savedInstanceState){
        mMapView = dataBinding.map;
        mMapView.onCreate(savedInstanceState);
        geocoderSearch = new GeocodeSearch(this);
        mAMap = mMapView.getMap();
        // 设置定位监听
        mAMap.setOnMapLoadedListener(this);
        mAMap.setOnMarkerClickListener(this);
        mAMap.setOnMapClickListener(this);

        mAMap.setLocationSource(this);
        //设置地图拖动监听
        mAMap.setOnCameraChangeListener(this);
        // 绑定marker拖拽事件
        //mAMap.setOnMarkerDragListener(this);
        //逆编码监听事件
        geocoderSearch.setOnGeocodeSearchListener(this);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.img_map_person));// 设置小蓝点的图标
        //myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(zoomToNumber)); //缩放比例
        //添加一个圆
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.radius(20.0f);
        mAMap.addCircle(circleOptions);

        //设置amap的属性
        UiSettings settings = mAMap.getUiSettings();
        settings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        location = aMapLocation;
        if (mListener != null && location != null) {
            if (location != null && location.getErrorCode() == 0) {
                mListener.onLocationChanged(location);// 显示系统箭头
                LatLng la = new LatLng(location.getLatitude(), location.getLongitude());
                setMarket(la, location.getCity(), location.getAddress());
                mLocationClient.stopLocation();
            }
        }
        else {
            ToastUtil.show("定位失败");
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        getAddress(latLng);
    }

    @Override
    public void onMapLoaded() {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }
        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        // 销毁定位
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mMapView.onDestroy();
        super.onDestroy();
    }

    private void setMarket(LatLng latLng, String title, String content) {
        if (mGPSMarker != null)  mGPSMarker.remove();
        //获取屏幕宽高
        WindowManager wm = this.getWindowManager();
        int width = (wm.getDefaultDisplay().getWidth()) / 2;
        int height = ((wm.getDefaultDisplay().getHeight()) / 2) - 80;
        markOptions = new MarkerOptions();
        markOptions.draggable(true);//设置Marker可拖动
        markOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.img_weather_dw))).anchor(0.5f, 0.7f);
        //设置一个角标
        mGPSMarker = mAMap.addMarker(markOptions);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        mGPSMarker.setTitle(title);
        mGPSMarker.setSnippet(content);
        //设置像素坐标
        mGPSMarker.setPositionByPixels(width, height);
        if (!UIUtils.isEmpty(content)) mGPSMarker.showInfoWindow();
        mMapView.invalidate();
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        latLng=cameraPosition.target;
        double latitude= latLng.latitude;
        double longitude= latLng.longitude;
        Log.d("getAddress=com==", JsonUtil.toJson(cameraPosition));
        Log.e("latitude",latitude+"");
        Log.e("longitude",longitude+"");
        mViewModel.getWeatherData(latitude+"",longitude+"");
        getAddress(latLng);
    }

    /**
     * 根据经纬度得到地址
     */
    public void getAddress(final LatLng latLon) {
//        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//        RegeocodeQuery query = new RegeocodeQuery(convertToLatLonPoint(latLonPoint), 500, GeocodeSearch.AMAP);
//        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        LatLonPoint latLonPoint = new LatLonPoint(latLon.latitude, latLon.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
        if(!UIUtils.isEmpty(latLonPoint)){
            Log.d("getAddress===", JsonUtil.toJson(latLonPoint));
        }
    }


    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress(); // 逆转地里编码不是每次都可以得到对应地图上的opi
                Log.d("getAddress===地址", addressName+"");
                dataBinding.bindTransparentToolBar.toolBarTvTitle.setText(addressName+"");
//              mAddressEntityFirst = new AddressSearchTextEntity(addressName, addressName, true, convertToLatLonPoint(mFinalChoosePosition));
                setMarket(latLng, location.getCity(), addressName);
            }
        }
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
    }
}
